package com.linxi.rpccompensation.config;

import com.linxi.rpccompensation.entity.SysPushLog;
import com.linxi.rpccompensation.service.PushLogService;
import com.linxi.rpccompensation.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 补偿策略定时任务
 * @author：lx
 * @date: 2021/09/25 下午 5:40
 * @Copyright： lx
 */
@Configuration
@EnableScheduling
public class CompensationStrategyTask {

	private static final long TIME_OUT = 5 * 60 * 1000;
	@Resource
	private HttpUtil httpUtil;
	@Resource
	private PushLogService pushLogService;
	private Logger logger = LoggerFactory.getLogger(CompensationStrategyTask.class);

	/**
	 * 5分钟检测消费失败的重新发送
	 * 在执行前对状态进行升级判断
	 */
	@Scheduled(cron = "0 0/1 * * * ?")
	private void resend() throws Exception {
		upgrade();
		Map<String, Object> map = new HashMap<String, Object>(1) {{
			put("status", "2");
		}};
		List<SysPushLog> list = pushLogService.listByMap(map);
		for (SysPushLog logVO : list) {
			if (pushLogService.doPush(logVO.getApi(), logVO.getData())) {
				logger.info("补偿消费成功！");
			} else {
				logger.info("补偿消费失败！");
				logVO.setStatus(4);
				pushLogService.updateById(logVO);
			}
		}
	}

	/**
	 * 5分钟检测超时5分钟没有接收到回应的已发送状态升级为消费失败
	 * 去除定时任务，避免多线程顺序执行问题
	 *
	 * @Scheduled(cron = "0 0/5 * * * ?")
	 */
	private void upgrade() {
		Map<String, Object> map = new HashMap<String, Object>(1) {{
			put("status", "1");
		}};
		List<SysPushLog> list = pushLogService.listByMap(map);
		for (SysPushLog logVO : list) {
			if (System.currentTimeMillis() - logVO.getTime().getTime() > TIME_OUT) {
				logVO.setStatus(2);
				pushLogService.updateById(logVO);
			}
		}
	}
}
